package com.kailing.bootbatch.piliang;

import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper;
import org.springframework.batch.item.file.mapping.DefaultLineMapper;
import org.springframework.batch.item.file.transform.DefaultFieldSetFactory;
import org.springframework.batch.item.file.transform.DelimitedLineTokenizer;
import org.springframework.core.io.ClassPathResource;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;

/**
 * <h3>springboot_batch_jdbc</h3>
 * <p>读文件</p>
 *
 * @author : hduong
 * @version : 1.0
 * @date : 2019-12-06 17:01
 **/
public class CommonFileReader<T> extends FlatFileItemReader<T> {

    private static final String DEFAULT_ENCODING = "UTF-8";

    private ClassPathResource classPathResource;

    public CommonFileReader(String fileName, Class cls, String delimeter, String encoding) {
        setEncoding(encoding == null ? DEFAULT_ENCODING : encoding);
        classPathResource = new ClassPathResource(fileName);
        setResource(classPathResource);
        //映射器
        DefaultLineMapper lineMapper = new DefaultLineMapper();
        //分隔符
        DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();
        //设置字段映射工厂
        tokenizer.setFieldSetFactory(new DefaultFieldSetFactory());
        Field[] fields = cls.getDeclaredFields();
        //获取所有的自u但名字
        List<String> fieldLists = new ArrayList<>(fields.length);
        for (Field field : fields) {
            if(!Modifier.isStatic(field.getModifiers())) {
                fieldLists.add(field.getName());
            }
        }
        String[] names = new String[fieldLists.size()];
        //将字段名 都设置到 tokenizer中去
        tokenizer.setNames(fieldLists.toArray(names));
        tokenizer.setDelimiter(delimeter == null ? "," : delimeter);
        lineMapper.setLineTokenizer(tokenizer);
        //设置对象映射器
        BeanWrapperFieldSetMapper wrapperFieldSetMapper = new BeanWrapperFieldSetMapper();
        wrapperFieldSetMapper.setTargetType(cls);

        //将对象映射器设置到 lineMapper 行映射器中
        lineMapper.setFieldSetMapper(wrapperFieldSetMapper);
        setLineMapper(lineMapper);
        setStrict(false);
    }
}
